package com.nkbh.sevenday.camera.camera1.activity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.nkbh.sevenday.camera.R;
import com.nkbh.sevenday.camera.utils.CommonUtil;
import com.nkbh.sevenday.camera.utils.ToastUtil;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 简单的拍照和前后摄像头切换功能
 */
public class CamareActivity extends AppCompatActivity implements View.OnClickListener {

    SurfaceView sfv;
    Button btn_camare,btn_cancle,btn_commit;
    ImageView img,img_camera;

    Camera camera;
    SurfaceHolder holder;

    int cameraPosition=1;//0表示后置摄像头，1表示前置摄像头

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camare);
        initView();
        startCamera(cameraPosition);
    }

    private void startCamera(int open) {

        //检测该设备是否有相机硬件
        if (!CommonUtil.checkCameraHardware(this)){
            ToastUtil.showMessage(this,"该设备没有相机硬件，不能调用相机相关的功能！！！");
            return;
        }
        //0表示后置摄像头，1表示前置摄像头
        camera= Camera.open(open);
        holder = sfv.getHolder();
        holder.addCallback(new SurfaceHolder.Callback() {
            //创建
            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                    //开始进行图片的预览
                    startPreview();
            }

            //改变
            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
                //停止旧的预览,开启新的预览
                camera.stopPreview();
                startPreview();
            }

            //释放
            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                //停止预览,释放资源
                stopCamera();

            }
        });
    }

    @Override
    protected void onPause() {
        super.onPause();
        stopCamera();
    }

    @Override
    protected void onResume() {
        super.onResume();
        startCamera(cameraPosition);
    }

    /**
     * 停止预览,释放资源
     */
    private void stopCamera() {
        if(camera!=null){
            camera.stopPreview();
            camera.release();
            camera=null;
        }
    }

    /**
     * 开始进行图片的预览
     */
    private void startPreview() {
        try {
            //相机与SurfaceView进行绑定
            camera.setPreviewDisplay(holder);
            //预览的图片旋转90
            camera.setDisplayOrientation(90);
            camera.startPreview();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    private void initView() {
        sfv=findViewById(R.id.sfv);
        btn_camare=findViewById(R.id.btn_camare);
        img=findViewById(R.id.img);
        btn_cancle=findViewById(R.id.btn_cancle);
        btn_commit=findViewById(R.id.btn_commit);
        img_camera=findViewById(R.id.img_camera);
        btn_camare.setOnClickListener(this);
        btn_commit.setOnClickListener(this);
        btn_cancle.setOnClickListener(this);
        img_camera.setOnClickListener(this);
    }

    /**
     * 前置摄像头和后置摄像头切换
     */
    public void frontOrBackCamera() {
        int CammeraIndex = 0;
        if (cameraPosition==0){
            CammeraIndex=CommonUtil.FindFrontCamera();
            if (CammeraIndex==-1){
                ToastUtil.showMessage(this,"没有前置摄像头");
                return;
            }
        }
        if (cameraPosition==1){
            CammeraIndex=CommonUtil.FindBackCamera();
            if(CammeraIndex==-1){
                ToastUtil.showMessage(this,"没有后置摄像头");
                return;
            }
        }
        cameraPosition=CammeraIndex;
        //TODO 待完善
        camera.stopPreview();
        camera.release();
        camera=Camera.open(cameraPosition);
        try {
            camera.setPreviewDisplay(holder);
            camera.setDisplayOrientation(90);
            camera.startPreview();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_camare:
                takePic();
                break;
            case R.id.btn_cancle:
                img.setVisibility(View.GONE);
                btn_camare.setVisibility(View.VISIBLE);
                btn_cancle.setVisibility(View.INVISIBLE);
                btn_commit.setVisibility(View.INVISIBLE);
                startPreview();
                break;

            case R.id.btn_commit:

                break;

            case R.id.img_camera:
                frontOrBackCamera();
                break;
        }
    }

    /**
     * 拍照
     */
    private void takePic() {
        //设置相机的各种参数
        Camera.Parameters parameters=camera.getParameters();
        //对焦的方式
        parameters.setFocusMode(Camera.Parameters.ANTIBANDING_AUTO);
        //照片的类型
        parameters.setPictureFormat(ImageFormat.JPEG);
        //对焦监听
        camera.autoFocus(new Camera.AutoFocusCallback() {
            @Override
            public void onAutoFocus(boolean success, Camera camera) {
                //对焦成功
                if(success){
                    //第一个参数ShutterCallback响应快门的接口，
                    // 第二个参数PictureCallback接收raw格式的图片数据，
                    // 第三个参数PictureCallback接收jpeg格式的图片数据
                    camera.takePicture(null,null,cameraCallBack);
                }else{
                    Toast.makeText(CamareActivity.this,"对焦失败!",Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    /**
     * 拍照成功回调函数*/
    private Camera.PictureCallback cameraCallBack=new Camera.PictureCallback() {
        @Override
        public void onPictureTaken(byte[] data, Camera camera) {
            startPreview();

            //先验证手机是否有sdcard
            String status= Environment.getExternalStorageState();
            if(!status.equals(Environment.MEDIA_MOUNTED))
            {
                Toast.makeText(getApplicationContext(),"你的sd卡不可用。",Toast.LENGTH_SHORT).show();
                return;
            }
            //大部分手机拍照都是存到这个路径
            String filePath=Environment.getExternalStorageDirectory().getPath()+"/DCIM/Camera/";
            String picturePath=System.currentTimeMillis()+".jpg";
            File file=new File(filePath,picturePath);
            try{
                //存到本地相册
                FileOutputStream fileOutputStream=new FileOutputStream(file);
                fileOutputStream.write(data);
                fileOutputStream.close();

                //显示图片
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inSampleSize = 2;
                Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, options);
                img.setVisibility(View.VISIBLE);
                btn_camare.setVisibility(View.INVISIBLE);
                btn_cancle.setVisibility(View.VISIBLE);
                btn_commit.setVisibility(View.VISIBLE);
                img.setImageBitmap(bitmap);
            }catch (FileNotFoundException e){
                e.printStackTrace();
            }catch (IOException e){
                e.printStackTrace();
            }

        }
    };
}
